package com.zhangtao.demo.controller;

import com.zhangtao.demo.common.config.GloableConfig;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhangtao.demo.common.util.ThrowableUtil;

@Controller
public class IndexContorller {
	private static Logger logger = LogManager.getLogger(IndexContorller.class);

	private static final int BUFF_SIZE = 1024 * 10;

	@Autowired
	private GloableConfig gconfig;

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home() {
		return "index";
	}

	@RequestMapping(value = "/utils", method = RequestMethod.GET)
	public String utilHome() {
		return "utils";
	}

	@RequestMapping(value = "/jedis-gui", method = RequestMethod.GET)
	public String jedisGuiHome() {
		return "jedis-gui";
	}

	@RequestMapping(value = "/voice-test", method = RequestMethod.GET)
	public String voiceTestGuiHome() {
		return "voice-test";
	}

	@RequestMapping(value = "/gamePage", method = RequestMethod.GET)
	public String gamePage() {
		return "lottery-turntable";
	}

	@RequestMapping(value = "/gameManage", method = RequestMethod.GET)
	public String gameManage() {
		return "lottery-turntable-manager";
	}

	// @GetMapping(value = "/remoteServiceFile/{fileName}")
	public void downloadFile(@PathVariable String fileName, HttpServletRequest request, HttpServletResponse response) {
		String fullPath = gconfig.getLocalResourcePath() + File.separator + fileName;
//		String osName = System.getProperty("os.name");
//		if (osName.contains("Windows")) {
//			fullPath = "d:" + fullPath;
//		}
		logger.info("---download path: " + fullPath);
		File downloadFile = new File(fullPath);
		if (!downloadFile.exists()) {
			logger.error("文件不存在");
			return;
		}
		System.out.println(downloadFile.getAbsolutePath());
		long fSize = downloadFile.length();

		response.reset();
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/x-download");

		response.setHeader("Accept-Ranges", "bytes");

		// set headers for the response
		String headerKey = "Content-Disposition";
		String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
		response.setHeader(headerKey, headerValue);

		// Copy the stream to the response's output stream.
		try (InputStream is = new FileInputStream(fullPath); OutputStream os = response.getOutputStream();) {

			long start = 0;
			long end = fSize;
			if (null != request.getHeader("Range")) {
				// 断点续传
				response.setStatus(HttpStatus.PARTIAL_CONTENT.value());
				try {
					logger.info("Range::: " + request.getHeader("Range"));
					String range = request.getHeader("Range").replaceAll("bytes=", "");
					if (range.endsWith("-")) {
						start = Long.parseLong(range.replace("-", ""));
						end = fSize;
					} else {
						int idx = range.indexOf("-");
						start = Long.parseLong(range.substring(0, idx));
						end = Long.parseLong(range.substring(idx + 1));
					}
				} catch (NumberFormatException e) {
					start = 0;
					end = fSize;
				}
			}

			if (start > fSize) {
				start = fSize;
			}
			if (end > fSize) {
				end = fSize;
			}
			if (start > end) {
				end = start;
			}

			String contentRange = new StringBuffer("bytes ").append(start).append("-").append(end).append("/")
					.append(fSize).toString();
			response.setHeader("Content-Range", contentRange);
			response.setHeader("Content-Length", String.valueOf(end - start));
			is.skip(start);
			byte[] buffer = new byte[BUFF_SIZE];
			int length = 0;
			long contentLen = end - start;
			do {
				if (BUFF_SIZE <= contentLen) {
					length = is.read(buffer, 0, buffer.length);
					os.write(buffer, 0, length);
					contentLen = contentLen - length;
				} else {
					length = is.read(buffer, 0, (int) contentLen);
					os.write(buffer, 0, length);
					break;
				}
			} while (true);
			response.flushBuffer();
		} catch (IOException e) {
			logger.error(ThrowableUtil.getErrorInfoFromThrowable(e));
		}
	}
}
